package com.yuan.studemo.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuan.studemo.common.Constants;
import com.yuan.studemo.common.Result;
import com.yuan.studemo.controller.dto.StuinfoDto;
import com.yuan.studemo.entity.Stuinfo;
import com.yuan.studemo.service.IStuinfoService;
import com.yuan.studemo.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 学生 前端控制器
 * </p>
 *
 * @author Yuan
 * @since 2022-05-19
 */
@RestController
@RequestMapping("/stuinfo")
public class StuinfoController {

//    @Value("${files.upload.path}")
//    private String filesUploadPath;

    @Resource
    private IStuinfoService stuinfoService;

    @PostMapping("/login")
    public Result login(@RequestBody StuinfoDto stuinfoDto) {
        String stuId = stuinfoDto.getStuId();
        String password = stuinfoDto.getPassword();
        //校验是否为空
        if (StrUtil.isBlank(stuId) || StrUtil.isBlank(password)) {
            return Result.error(Constants.CODE_400, "参数错误");
        }
        StuinfoDto dto = stuinfoService.login(stuinfoDto);
        return Result.success(dto);
    }

    @PostMapping
    public Result save(@RequestBody Stuinfo stuinfo) {
        //新增或者更新
        return Result.success(stuinfoService.saveOrUpdate(stuinfo));
    }

    //删除数据
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(stuinfoService.removeById(id));
    }

    //批量删除
    @PostMapping("del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(stuinfoService.removeBatchByIds(ids));
    }

    //查询所有数据
    @GetMapping("/")
    public Result findAll() {
        return Result.success(stuinfoService.list());
    }

    //根据id查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(stuinfoService.getById(id));
    }

    //根据id查询
    @GetMapping("/stuId/{stuId}")
    public Result findOne(@PathVariable String stuId) {
        QueryWrapper<Stuinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("stuId",stuId);
        return Result.success(stuinfoService.getOne(queryWrapper));
    }

    //分页查询
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                  @RequestParam Integer pageSize,
                                  @RequestParam(defaultValue = "") String name,
                                  @RequestParam(defaultValue = "") String stuId,
                                  @RequestParam(defaultValue = "") String sex) {

        QueryWrapper<Stuinfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        if (!"".equals(stuId)) {
            queryWrapper.like("stuId", stuId);
        }
        if (!"".equals(sex)) {
            queryWrapper.like("sex", sex);
        }

        //获取当前用户信息
        Stuinfo currentStuinfo = TokenUtils.getCurrentStuinfo();
        System.out.println(currentStuinfo.getName());

        return Result.success(stuinfoService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    //文件导出接口
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        //从数据库查询出所有数据
        List<Stuinfo> list = stuinfoService.list();
        // 通过工具类创建writer 写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("addtime", "添加时间");
        writer.addHeaderAlias("stuId", "学号");
        writer.addHeaderAlias("password", "密码");
        writer.addHeaderAlias("name", "学生姓名");
        writer.addHeaderAlias("sex", "性别");
        writer.addHeaderAlias("birth", "出生日期");
        writer.addHeaderAlias("phone", "联系电话");
        writer.addHeaderAlias("grade", "班级");

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("学生信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();
    }

    //文件导入接口
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<Stuinfo> list = reader.readAll(Stuinfo.class);

        stuinfoService.saveBatch(list);
        return Result.success(true);
    }
}

